﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QuickApp.MVCControl;
using Resto.CostControl.Core;
using System.Data.Entity;
using QuickApp.Core;
using Resto.CostControl.Core.Models.SysSettings;
using QuickApp.MVCControl.Tree;
using QuickApp.MVCControl.Form;
using QuickApp.Core.Models;
using Resto.CostControl.Core.Models;
using Resto.CostControl.Core.Enums;
using System.Data;
using Resto.CostControl.Core.Services;

namespace Resto.CostControl.Web.Controllers
{
    public class SysSettingController : Controller
    {
        [Ninject.Inject]
        public IUnitOfWork unitOfWork { get; set; }

        #region 角色管理
        [Ninject.Inject]
        public IRepository<RoleInfo> roleRepo { get; set; }
        [Ninject.Inject]
        public IRepository<RoleUserRelation> roleUserRepo { get; set; }

        //[xEasyAppAuthorize(PagePrivilegeCode = Constants.SystemManage_Role_PagePrivilegeCode)]
        public ActionResult RoleList()
        {
            return View();
        }

        [HttpPost]
        public JsonResult RoleList(DWZPageInfo pager, DWZQueryModel where)
        {
            var list = roleRepo.GetPageable(pager.ToPageInfo(), where);
            var fdata = pager.ToFlexiGridData<RoleInfo>(list.Page.ToList(), list.Total);
            return Json(fdata);
        }

        public ActionResult EditRole(string Id)
        {
            RoleInfo data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = roleRepo.Find(Id);
            }
            else
            {
                data = new RoleInfo();
            }
            return View(data);
        }

        //public ContentResult ValidRoleCode(string RoleCode)
        //{
        //    bool isValid = sysManageService.ValidRoleCode(RoleCode);
        //    return Content(isValid ? "true" : "false", "application/json");
        //}

        [HttpPost]
        public JsonResult SaveRoleInfo(RoleInfo data)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrWhiteSpace(data.Id))
                {
                    data.Id = Guid.NewGuid().ToString();
                    data.IsSystem = false;
                    roleRepo.Insert(data);
                }
                else
                {
                    var oldData = roleRepo.Find(data.Id);
                    TryUpdateModel(oldData);
                }

                unitOfWork.Commit();
            }

            var result = new JsonReturnMessages
            {
                IsSuccess = true,
                Msg = "操作成功",
            };
            return Json(result);
        }

        [HttpPost]
        public JsonResult DeleteRole(string id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(id))
            {
                try
                {
                    roleRepo.Delete(id);
                    unitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                catch (Exception ex)
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败:" + ex.Message;
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }

            return Json(msg);
        }

        [HttpPost]
        public JsonResult DeleteRoleUser(string RoleCode, string userids)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            try
            {
                roleUserRepo.DeleteAll(r => r.RoleCode == RoleCode && userids.Contains(r.UserId));
                unitOfWork.Commit();
                msg.IsSuccess = true;
                msg.Msg = "操作成功";
            }
            catch (Exception ex)
            {
                msg.IsSuccess = false;
                msg.Msg = "操作失败：" + ex.Message;
            }
            return Json(msg);
        }



        [HttpPost]
        public JsonResult AddRoleUser(string roleCode, string userids)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            try
            {
                // 查找角色
                var role = roleRepo.Find(r => r.RoleCode == roleCode);
                if (role != null)
                {
                    // 查出所有选中用户
                    var ids = userids.Split(',');
                    var userlist = userRepo.FindAll(u => ids.Contains(u.UserCode));

                    // 插入数据
                    foreach (var user in userlist)
                    {
                        roleUserRepo.Insert(new RoleUserRelation
                        {
                            Id = Guid.NewGuid().ToString(),
                            RoleID = role.Id,
                            RoleCode = role.RoleCode,
                            UserId = user.Id,
                            UserCode = user.UserCode,
                        });
                    }

                    unitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                else
                {
                    msg.IsSuccess = true;
                    msg.Msg = string.Format("指定的角色{0}不存在或者已经被删除", roleCode);
                }
            }
            catch (Exception ex)
            {
                msg.IsSuccess = false;
                msg.Msg = "操作失败：" + ex.Message;
            }
            return Json(msg);
        }

        public ActionResult SetRoleUser(string id)
        {
            return View();
        }

        public ActionResult SetRolePrivilege(string roleCode)
        {
            ViewBag.RoleCode = roleCode;
            return View();
        }

        [HttpPost]
        public JsonResult SetRolePrivilege(string roleCode, string addids, string minusids)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            try
            {
                // 查找角色
                var role = roleRepo.Find(r => r.RoleCode == roleCode);
                if (role != null)
                {
                    // 查出角色的已有所有权限
                    var existsPris = rolePriRepo.FindAll(r => r.RoleCode == roleCode).ToList();

                    // 查出待添加的所有权限
                    var ids = addids.Split(',');
                    var newPris = privilegeRepo.FindAll(r => ids.Contains(r.Id)).ToList();

                    // 插入数据
                    foreach (var pri in newPris)
                    {
                        // 如果没有找到则插入
                        if (existsPris.Count(p => p.PrivilegeId == pri.Id) == 0)
                        {
                            rolePriRepo.Insert(new RolePrivilegeRelation
                            {
                                Id = Guid.NewGuid().ToString(),
                                RoleID = role.Id,
                                RoleCode = role.RoleCode,
                                PrivilegeId = pri.Id,
                                PrivilegeCode = pri.PrivilegeCode,
                            });
                        }
                    }

                    // 删除待删除的所有权限
                    var deleteIds = minusids.Split(',');
                    rolePriRepo.DeleteAll(p => deleteIds.Contains(p.PrivilegeId));

                    unitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                else
                {
                    msg.IsSuccess = true;
                    msg.Msg = string.Format("指定的角色{0}不存在或者已经被删除", roleCode);
                }
            }
            catch (Exception ex)
            {
                msg.IsSuccess = false;
                msg.Msg = "操作失败：" + ex.Message;
            }
            return Json(msg);
        }

        #endregion

        #region 权限管理
        [Ninject.Inject]
        public IRepository<Privilege> privilegeRepo { get; set; }
        [Ninject.Inject]
        public IRepository<RolePrivilegeRelation> rolePriRepo { get; set; }

        //[xEasyAppAuthorize(PagePrivilegeCode = Constants.SystemManage_Privilege_PagePrivilegeCode)]
        public ActionResult PrivilegeList()
        {
            return View();
        }

        [HttpPost]
        public JsonResult PrivilegeList(string parentId, DWZPageInfo pager, DWZQueryModel where)
        {
            // 添加ParentId的检索条件
            where.AddItem("ParentId", parentId == "" ? null : parentId);

            // 分页查询数据
            var list = privilegeRepo.GetPageable(pager.ToPageInfo(), where);
            var fdata = pager.ToFlexiGridData<Privilege>(list.Page.ToList(), list.Total);
            return Json(fdata);
        }

        [HttpPost]
        public JsonResult PrivilegeTree(string Id)
        {
            var nodes = new List<JsonTreeNode>();
            var parentIds = privilegeRepo.FindAll(p => p.ParentId != null).Select(p => p.ParentId).Distinct().ToList();
            Action<List<Privilege>, List<JsonTreeNode>, bool> BuildChildrenNodes = (list, cNodes, isComplete) =>
            {
                foreach (var item in list)
                {
                    var node = new JsonTreeNode();
                    node.id = item.Id;
                    node.text = item.PrivilegeName;
                    node.value = item.Id;
                    node.isexpand = isComplete;
                    node.showcheck = false;
                    node.complete = isComplete;
                    node.hasChildren = parentIds.Contains(item.Id) || item.Id == "";
                    cNodes.Add(node);
                }
            };

            if (Id == null)
            {
                // 增加第一层虚拟节点
                BuildChildrenNodes(new List<Privilege> { new Privilege { Id = "", PrivilegeName = "权限管理" } }, nodes, true);

                // 增加第二层节点（根节点）
                var fList = privilegeRepo.FindAll(o => o.ParentId == null).OrderBy(o => o.SeqNo).ToList();
                BuildChildrenNodes(fList, nodes[0].ChildNodes, true);

                // 增加第三层节点
                var rootIds = fList.Select(p => p.Id);
                var SList = privilegeRepo.FindAll(o => rootIds.Contains(o.ParentId)).OrderBy(o => o.SeqNo).ToList();
                foreach (var snode in nodes[0].ChildNodes)
                {
                    BuildChildrenNodes(SList.FindAll(p => p.ParentId == snode.id), snode.ChildNodes, false);
                }
            }
            else
            {
                var list = privilegeRepo.FindAll(o => string.IsNullOrEmpty(Id) ? o.ParentId == null : o.ParentId == Id)
                    .OrderBy(o => o.SeqNo).ToList();
                BuildChildrenNodes(list, nodes, false);
            }
            return Json(nodes);

            //var nodes = new List<JsonTreeNode>();
            //List<Privilege> allPrivileges = null;
            //if (string.IsNullOrEmpty(Id))
            //{
            //    allPrivileges = privilegeRepo.FindAll().ToList();
            //}
            //else
            //{
            //    allPrivileges = privilegeRepo.FindAll(p => p.FullPath.Contains(Id)).ToList();
            //}
            //var rootNode = new JsonTreeNode();
            //// 虚拟节点
            //rootNode.id = "";
            //rootNode.text = "权限类型";
            //rootNode.value = "";
            //rootNode.isexpand = true;
            //rootNode.showcheck = false;
            //rootNode.complete = true;
            //rootNode.hasChildren = privilegeRepo.FindAll(p => p.ParentId == null).Count() > 0;

            //var list = allPrivileges.Where(p => string.IsNullOrEmpty(Id) ? p.ParentId == null : p.ParentId == Id);
            //foreach (var item in list)
            //{
            //    JsonTreeNode node = new JsonTreeNode();
            //    node.id = item.Id;
            //    node.text = item.PrivilegeName;
            //    node.value = item.Id;
            //    node.isexpand = true;
            //    node.showcheck = false;
            //    node.complete = true;
            //    node.hasChildren = allPrivileges.Count(p => p.ParentId == item.Id) > 0;
            //    BuildPrivilegeTreeNode(node, allPrivileges, item.Id);
            //    nodes.Add(node);
            //}
            //return Json(nodes);
        }

        public ActionResult EditPrivilege(string Id, string parentId)
        {
            Privilege data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = privilegeRepo.Find(Id);
            }
            else
            {
                data = new Privilege();
            }

            // 设置父节点对象
            var parentData = privilegeRepo.Find(parentId);
            if (parentData != null)
            {
                data.ParentName = parentData.PrivilegeName;
                data.ParentCode = parentData.PrivilegeCode;
                data.ParentId = parentData.Id;
            }
            else
            {
                data.ParentName = "根权限";
            }

            return View(data);
        }

        [HttpPost]
        public JsonResult DeletePrivilege(string id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(id))
            {
                try
                {
                    privilegeRepo.Delete(id);
                    unitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                catch
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败,请稍后重试！";
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }
            return Json(msg);
        }

        [HttpPost]
        public JsonResult SavePrivilege(Privilege data)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrWhiteSpace(data.Id))
                {
                    data.Id = Guid.NewGuid().ToString();
                    privilegeRepo.Insert(data);
                }
                else
                {
                    var oldData = privilegeRepo.Find(data.Id);
                    TryUpdateModel(oldData);
                }

                unitOfWork.Commit();
            }

            var result = new JsonReturnMessages
            {
                IsSuccess = true,
                Msg = "操作成功",
            };
            return Json(result);
        }

        public JsonResult ValidPrivilegeCode(string Id, string PrivilegeCode)
        {
            bool isValid = privilegeRepo.Find(p => p.PrivilegeCode == PrivilegeCode && p.Id != Id) == null;
            return Json(isValid, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 递归构建权限树的数据结构
        /// </summary>
        private void BuildPrivilegeTreeNode(JsonTreeNode parentNode, List<Privilege> allPrivileges, string parentId)
        {
            var childList = allPrivileges.Where(p => p.ParentId == parentId);
            foreach (Privilege child in childList)
            {
                JsonTreeNode node = new JsonTreeNode();
                node.id = child.Id;
                node.text = child.PrivilegeName;
                node.value = child.Id;
                node.isexpand = true;
                node.showcheck = false;
                node.complete = true;
                node.hasChildren = allPrivileges.Count(p => p.ParentId == child.Id) > 0;
                // 递归子节点
                BuildPrivilegeTreeNode(parentNode, allPrivileges, child.Id);
                // 将子节点添加到父节点中
                parentNode.ChildNodes.Add(node);
            }
        }

        [HttpPost]
        public JsonResult GetRolePrivileges(string roleCode, string Id)
        {
            var nodes = new List<JsonTreeNode>();
            var roleList = rolePriRepo.FindAll(x => x.RoleCode == roleCode).ToList();
            if (string.IsNullOrEmpty(Id))
            {
                // 增加最根节点
                var rootList = privilegeRepo.FindAll(o => o.ParentId == null);
                foreach (var root in rootList)
                {
                    JsonTreeNode node = new JsonTreeNode();
                    node.id = root.Id;
                    node.text = root.PrivilegeName;
                    node.isexpand = true;
                    node.showcheck = true;
                    node.complete = true;
                    node.hasChildren = true;
                    node.checkstate = roleList.Count(x => x.PrivilegeId == root.Id) > 0 ? (byte)1 : (byte)0;
                    node.value = node.checkstate == 1 ? "true" : "false";
                    GetChildRolePrivilege(root.Id, node.ChildNodes, roleList);
                    nodes.Add(node);
                }
            }
            else
            {
                GetChildRolePrivilege(Id, nodes, roleList);
            }
            return Json(nodes);
        }

        private void GetChildRolePrivilege(string parentId, List<JsonTreeNode> parentNodes, List<RolePrivilegeRelation> roleList)
        {
            var glist = privilegeRepo.FindAll(o => o.ParentId == parentId);
            foreach (var item in glist)
            {
                JsonTreeNode gnode = new JsonTreeNode();
                gnode.id = item.Id;
                gnode.text = item.PrivilegeName;
                gnode.hasChildren = false;
                gnode.showcheck = true;
                gnode.checkstate = roleList.Count(x => x.PrivilegeId == item.Id) > 0 ? (byte)1 : (byte)0;
                gnode.value = gnode.checkstate == 1 ? "true" : "false";
                parentNodes.Add(gnode);
            }
        }

        //[xEasyAppAuthorize(PagePrivilegeCode = Constants.SystemManage_Authorization_PagePrivilegeCode)]
        //public ActionResult QueryAuthorization()
        //{
        //    return View();
        //}

        //[HttpPost]
        //public JsonResult QueryUserPrivilegeTree(FormCollection form)
        //{
        //    List<JsonTreeNode> treelist = new List<JsonTreeNode>();
        //    string usercode = form["UserCode"];
        //    string parentId = form["id"] ?? "";


        //    List<Privilege> list = sysManageService.GetUserPrivilegesByParentID(usercode, parentId);
        //    foreach (Privilege pri in list)
        //    {

        //        JsonTreeNode node = new JsonTreeNode();
        //        node.hasChildren = pri.HasChild;
        //        node.id = pri.PrivilegeCode;
        //        node.text = pri.PrivilegeName;
        //        node.value = pri.PrivilegeCode;
        //        if (parentId == "" && node.hasChildren)
        //        {
        //            List<Privilege> clist = sysManageService.GetUserPrivilegesByParentID(usercode, node.id);
        //            foreach (Privilege cpri in clist)
        //            {
        //                JsonTreeNode cnode = new JsonTreeNode();
        //                cnode.hasChildren = cpri.HasChild;
        //                cnode.id = cpri.PrivilegeCode;
        //                cnode.text = cpri.PrivilegeName;
        //                cnode.value = cpri.PrivilegeCode;
        //                node.ChildNodes.Add(cnode);
        //            }
        //            node.isexpand = true;
        //            node.complete = true;
        //        }
        //        treelist.Add(node);
        //    }
        //    return Json(treelist);
        //}
        //[HttpPost]
        //public JsonResult QueryPrivilegeRoles(FormCollection form)
        //{
        //    string pcode = form["pCode"];// 权限标识
        //    string usercode = form["userCode"];// 权限标识

        //    List<RoleInfo> list = sysManageService.QueryUserPrivilegeRoles(usercode, pcode);
        //    List<string[]> rlist = new List<string[]>();
        //    foreach (RoleInfo role in list)
        //    {
        //        rlist.Add(new string[] { role.RoleID.ToString(), role.RoleCode, role.RoleName, role.IsSystem ? "1" : "0" });
        //    }
        //    return Json(rlist);
        //}
        #endregion

        #region 用户管理
        [Ninject.Inject]
        public IRepository<UserInfo> userRepo { get; set; }

        //[xEasyAppAuthorize(PagePrivilegeCode = Constants.SystemManage_User_PagePrivilegeCode)]
        public ActionResult UserList()
        {
            return View();
        }

        [HttpPost]
        public JsonResult OrgInfoTreeList(string Id)
        {
            var rootNode = new JsonTreeNode();
            List<Organization> orgs = null;
            if (string.IsNullOrWhiteSpace(Id))
            {
                orgs = OrgRepo.FindAll().ToList();
            }
            else
            {
                orgs = OrgRepo.FindAll(p => p.FullPath.Contains(Id)).ToList();
            }

            // 增加根节点，只是个技巧，用于获取子节点的数据
            if (string.IsNullOrWhiteSpace(Id))
            {
                rootNode.id = "";
                rootNode.text = "根节点";
                rootNode.value = "";
            }
            else
            {
                // 生成指定Id的根节点
                var org = orgs.FirstOrDefault(p => p.Id == Id);
                if (org != null)
                {
                    rootNode.id = org.Id;
                    rootNode.text = org.OrgName;
                    rootNode.value = org.Id;
                }
                else
                {
                    throw new ArgumentException(string.Format("找不到指定OrgId的部门信息({0})", Id));
                }
            }
            rootNode.isexpand = true;
            rootNode.showcheck = false;
            rootNode.complete = true;
            rootNode.hasChildren = true;

            // 递归子节点
            if (rootNode.hasChildren)
            {
                BuildOrgTreeNode(rootNode, orgs, rootNode.value);
            }

            // 如果为空，则增加所有用户这个虚拟节点，显示所有用户
            if (string.IsNullOrEmpty(rootNode.id))
            {
                var childNode = new JsonTreeNode();
                childNode.id = "";
                childNode.text = "所有用户";
                childNode.value = "";
                rootNode.ChildNodes.Add(childNode);
            }

            return Json(rootNode.ChildNodes);
        }

        [HttpPost]
        public JsonResult OrgUserList(string parentId, DWZPageInfo pager, DWZQueryModel where)
        {
            // 添加ParentId的检索条件
            if (!string.IsNullOrWhiteSpace(parentId))
            {
                where.AddItem("OrgId", parentId == "" ? null : parentId);
            }

            // 分页查询数据
            var list = userRepo.GetPageable(pager.ToPageInfo(), where);
            var fdata = pager.ToFlexiGridData<UserInfo>(list.Page.ToList(), list.Total);

            return Json(fdata);
        }

        public ActionResult EditUser(string Id, string parentId)
        {
            UserInfo data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = userRepo.Find(Id);
            }
            else
            {
                data = new UserInfo();
                data.SeqNo = 9999;
                data.AccountState = AccountState.Normal.ToString();
            }

            // 设置父节点对象
            var org = OrgRepo.Find(data.OrgId ?? parentId);
            if (org != null)
            {
                data.OrgId = org.Id;
                data.OrgCode = org.OrgCode;
                data.OrgName = org.OrgName;
            }

            return View(data);
        }

        [HttpPost]
        public JsonResult SaveUserInfo(UserInfo user, SampleData data)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            try
            {
                if (string.IsNullOrWhiteSpace(user.AccountState))
                {
                    user.AccountState = "false";
                }
                if (string.IsNullOrWhiteSpace(user.Id))
                {
                    user.Id = Guid.NewGuid().ToString();
                    userRepo.Insert(user);
                }
                else
                {
                    var oldData = userRepo.Find(user.Id);
                    TryUpdateModel(oldData);
                }

                unitOfWork.Commit();

                msg.IsSuccess = true;
                msg.Msg = "操作成功";
            }
            catch
            {
                msg.IsSuccess = false;
                msg.Msg = "操作失败,请稍后重试！";
            }
            return Json(msg);
        }

        public JsonResult ValidUserCode(string Id, string UserCode)
        {
            bool isValid = userRepo.Find(p => p.UserCode == UserCode && p.Id != Id) == null;
            return Json(isValid, JsonRequestBehavior.AllowGet);
        }

        public JsonResult QueryOrgTree(string Id)
        {
            var nodes = new List<JsonTreeNode>();
            List<Organization> orgs = null;
            orgs = OrgRepo.FindAll().ToList();

            if (string.IsNullOrWhiteSpace(Id))
            {
                Id = "-1";
            }
            var list = orgs.Where(p => p.ParentId == Id).ToList();

            foreach (var item in list)
            {
                JsonTreeNode node = new JsonTreeNode();
                node.id = item.Id;
                node.text = item.OrgName;
                node.value = item.Id;
                node.hasChildren = false;
                if (orgs.Count(p => p.ParentId == item.Id) > 0)
                {
                    node.hasChildren = true;
                }
                nodes.Add(node);
            }
            return Json(nodes);
        }

        [HttpPost]
        public JsonResult DeleteUserInfo(string id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(id))
            {
                try
                {
                    userRepo.Delete(id);
                    unitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                catch //(Exception ex)
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败,请稍后重试！";
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }
            return Json(msg);
        }

        public ActionResult SetOrg(int mode, string extid)
        {
            ViewBag.IsMuliSelect = mode == 1;
            ViewBag.Url = Url.Action("OrgInfoTreeList", new { ExtId = extid });
            return View();
        }

        public ActionResult SingleSelectUser()
        {
            ViewBag.IsMuliSelect = false;
            return View();
        }

        #endregion

        #region 部门管理
        [Ninject.Inject]
        public IRepository<Organization> OrgRepo { get; set; }

        public ActionResult OrgList()
        {
            return View();
        }

        [HttpPost]
        public JsonResult OrgList(string parentId, DWZPageInfo pager, DWZQueryModel where)
        {
            // 添加ParentId的检索条件
            where.AddItem("ParentId", parentId == "" ? null : parentId);

            // 分页查询数据
            var list = OrgRepo.GetPageable(pager.ToPageInfo(), where);
            var fdata = pager.ToFlexiGridData<Organization>(list.Page.ToList(), list.Total);

            return Json(fdata);
        }

        [HttpPost]
        public JsonResult OrgTree(string Id)
        {
            var rootNode = new JsonTreeNode();
            List<Organization> orgs = null;
            if (string.IsNullOrWhiteSpace(Id))
            {
                orgs = OrgRepo.FindAll().OrderBy(o => o.SeqNo).ToList();
            }
            else
            {
                orgs = OrgRepo.FindAll(p => p.FullPath.Contains(Id)).OrderBy(o => o.SeqNo).ToList();
            }


            // 判断是否为组织机构这个虚拟节点
            if (string.IsNullOrWhiteSpace(Id))
            {
                rootNode.id = "";
                rootNode.text = "组织机构";
                rootNode.value = "";
            }
            else
            {
                // 生成指定Id的根节点
                var org = orgs.FirstOrDefault(p => p.Id == Id);
                if (org != null)
                {
                    rootNode.id = org.Id;
                    rootNode.text = org.OrgName;
                    rootNode.value = org.Id;
                }
                else
                {
                    throw new ArgumentException(string.Format("找不到指定OrgId的部门信息({0})", Id));
                }
            }
            rootNode.isexpand = true;
            rootNode.showcheck = false;
            rootNode.complete = true;
            rootNode.hasChildren = orgs.Count(p => rootNode.value == "" ? p.ParentId == null : p.ParentId == rootNode.value) > 0;

            // 递归子节点
            if (rootNode.hasChildren)
            {
                BuildOrgTreeNode(rootNode, orgs, rootNode.value);
            }

            return Json(Id != null ? rootNode.ChildNodes : new List<JsonTreeNode> { rootNode });
        }

        public ActionResult EditOrg(string Id, string parentId)
        {
            Organization data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = OrgRepo.Find(Id);
            }
            else
            {
                data = new Organization();
                data.SeqNo = 9999;
                data.OrgType = string.IsNullOrEmpty(parentId) ? OrgType.Unit.ToString() : OrgType.Dept.ToString();
            }

            // 设置父节点对象
            var parentOrg = OrgRepo.Find(data.ParentId);
            if (parentOrg != null)
            {
                data.ParentName = parentOrg.OrgName;
                data.ParentCode = parentOrg.OrgCode;
                data.ParentId = parentOrg.Id;
            }
            else
            {
                data.ParentName = "组织机构";
            }

            return View(data);
        }

        [HttpPost]
        public JsonResult SaveOrg(Organization data, string parentId)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            try
            {
                if (ModelState.IsValid)
                {
                    if (string.IsNullOrWhiteSpace(data.Id))
                    {
                        data.Id = Guid.NewGuid().ToString();

                        // 设置全路径
                        var parent = OrgRepo.Find(parentId);
                        var parentFullPath = parent == null ? string.Empty : parent.FullPath;
                        data.SetFullPath(parentFullPath);

                        OrgRepo.Insert(data);
                    }
                    else
                    {
                        var oldData = OrgRepo.Find(data.Id);
                        TryUpdateModel(oldData);
                    }

                    unitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
            }
            catch (Exception ex)
            {
                msg.IsSuccess = false;
                msg.Msg = "操作失败：" + ex.Message;
            }
            return Json(msg);
        }

        [HttpPost]
        public JsonResult DeleteOrg(string id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(id))
            {
                try
                {
                    OrgRepo.Delete(id);
                    unitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                catch (Exception ex)
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败:" + ex.Message;
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }
            return Json(msg);
        }

        public JsonResult ValidOrgCode(string Id, string OrgCode)
        {
            bool isValid = OrgRepo.Find(p => p.OrgCode == OrgCode && p.Id != Id) == null;
            return Json(isValid, JsonRequestBehavior.AllowGet);
        }

        public ActionResult OrgUserList(string orgId)
        {
            ViewBag.OrgId = orgId;
            return View();
        }

        /// <summary>
        /// 递归构建部门树的数据结构
        /// </summary>
        private void BuildOrgTreeNode(JsonTreeNode parentNode, List<Organization> orgs, string parentId)
        {
            var childList = orgs.Where(p => parentId == "" ? p.ParentId == null : p.ParentId == parentId);
            foreach (var child in childList)
            {
                JsonTreeNode node = new JsonTreeNode();
                node.id = child.Id;
                node.text = child.OrgName;
                node.value = child.Id;
                node.isexpand = true;
                node.showcheck = false;
                node.complete = true;
                node.hasChildren = orgs.Count(p => p.ParentId == child.Id) > 0;
                // 递归子节点
                BuildOrgTreeNode(node, orgs, child.Id);
                // 将子节点添加到父节点中
                parentNode.ChildNodes.Add(node);
            }
        }
        #endregion

        #region 枚举类型管理

        [Ninject.Inject]
        public IRepository<EnumType> enumTypeRepo { get; set; }

        public ActionResult DictInfoList()
        {
            return View();
        }

        [HttpPost]
        public JsonResult EnumInfoList(string parentId, DWZPageInfo pager, DWZQueryModel where)
        {
            if (!string.IsNullOrWhiteSpace(parentId))
            {
                // 添加ParentId的检索条件
                where.AddItem("ParentId", parentId);
                var list = enumItemRepo.GetPageable(pager.ToPageInfo(), where);
                var fdata = pager.ToFlexiGridData<EnumItem>(list.Page.ToList(), list.Total);
                return Json(fdata);
            }
            else
            {
                var list = enumTypeRepo.GetPageable(pager.ToPageInfo(), where);
                var fdata = pager.ToFlexiGridData<EnumType>(list.Page.ToList(), list.Total);
                return Json(fdata);
            }
        }

        [HttpPost]
        public JsonResult EnumTree(string Id)
        {
            var rootNode = new JsonTreeNode();
            var EnumTypes = enumTypeRepo.FindAll().OrderBy(e => e.SeqNo).ToList(); // (p => !p.IsSystem);

            // 虚拟节点
            rootNode.id = "";
            rootNode.text = "枚举类型";
            rootNode.value = "";
            rootNode.isexpand = true;
            rootNode.showcheck = false;
            rootNode.complete = true;
            rootNode.hasChildren = EnumTypes.Count() > 0;

            foreach (var type in EnumTypes)
            {
                JsonTreeNode node = new JsonTreeNode();
                node.id = type.Id;
                node.text = type.TypeName;
                node.value = type.TypeCode;
                node.isexpand = true;
                node.showcheck = false;
                node.complete = true;
                node.hasChildren = false;
                rootNode.ChildNodes.Add(node);
            }
            return Json(Id != null ? rootNode.ChildNodes : new List<JsonTreeNode> { rootNode });
        }

        private void BuildDicTreeNode(JsonTreeNode parentNode, List<EnumItem> items, string parentId)
        {

            var childList = items.Where(p => p.ParentId == null ? p.TypeCode == parentId : p.ParentId == parentId);
            foreach (var child in childList)
            {
                JsonTreeNode node = new JsonTreeNode();
                node.id = child.Id;
                node.text = child.EnumName;
                node.value = child.Id;
                node.isexpand = true;
                node.showcheck = false;
                node.complete = true;
                node.hasChildren = items.Count(p => p.ParentId == child.Id) > 0;
                // 递归子节点
                if (node.hasChildren)
                {
                    BuildDicTreeNode(node, items, child.Id);
                }
                // 将子节点添加到父节点中
                parentNode.ChildNodes.Add(node);
            }
        }

        public ActionResult EditDictInfo(string Id)
        {
            EnumType data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = enumTypeRepo.Find(Id);
            }
            else
            {
                data = new EnumType();
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult SaveEnumInfo(EnumType di)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            try
            {
                di.IsSystem = false;

                if (string.IsNullOrWhiteSpace(di.Id))
                {
                    di.Id = Guid.NewGuid().ToString();
                    enumTypeRepo.Insert(di);
                }
                else
                {
                    var oldData = enumTypeRepo.Find(di.Id);
                    TryUpdateModel(oldData);
                }

                unitOfWork.Commit();
                msg.IsSuccess = true;
                msg.Msg = "操作成功";
            }
            catch (Exception ex)
            {
                msg.IsSuccess = false;
                msg.Msg = "操作失败：" + ex.Message;
            }
            return Json(msg);
        }

        [HttpPost]
        public JsonResult DeleteEnumInfo(string Id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();

            try
            {
                enumTypeRepo.Delete(Id);
                unitOfWork.Commit();
                msg.IsSuccess = true;
                msg.Msg = "操作成功";
            }
            catch (Exception ex)
            {
                msg.IsSuccess = false;
                msg.Msg = "操作失败:" + ex.Message;
            }

            return Json(msg);
        }

        #endregion

        #region 枚举子项管理

        [Ninject.Inject]
        public IRepository<EnumItem> enumItemRepo { get; set; }

        public ActionResult EditEnumItem(string Id, string parentId, string typeCode)
        {
            EnumItem data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = enumItemRepo.Find(Id);
                var entity = enumItemRepo.Find(data.ParentId);
                if (entity != null)
                {
                    data.ParentName = entity.EnumName;
                }
                if (data == null)
                {
                    data = new EnumItem();
                }
            }
            else
            {
                data = new EnumItem();
                data.SeqNo = 9999;

                if (!string.IsNullOrEmpty(parentId))
                {
                    var parentItem = enumItemRepo.Find(p => p.Id == parentId);
                    if (parentItem != null)
                    {
                        data.ParentId = parentItem.Id;
                        data.ParentCode = parentItem.EnumCode;
                        data.ParentName = parentItem.EnumName;
                    }
                }
                else
                {
                    // 设置Type类型
                    var type = enumTypeRepo.Find(t => t.TypeCode == typeCode);
                    if (type != null)
                    {
                        data.TypeCode = type.TypeCode;
                        data.TypeId = type.Id;
                    }
                }
            }

            // 设置父节点对象
            var parentDic = enumTypeRepo.Find(parentId);
            if (parentDic != null)
            {
                data.ParentCode = parentDic.TypeCode;
                data.ParentId = parentDic.Id;
            }

            return View(data);
        }

        [HttpPost]
        public JsonResult SaveEnumItemInfo(EnumItem di)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            try
            {
                if (string.IsNullOrWhiteSpace(di.Id))
                {
                    di.Id = Guid.NewGuid().ToString();
                    enumItemRepo.Insert(di);
                }
                else
                {
                    var oldData = enumItemRepo.Find(di.Id);
                    TryUpdateModel(oldData);
                }

                unitOfWork.Commit();
                msg.IsSuccess = true;
                msg.Msg = "操作成功";
            }
            catch (Exception ex)
            {
                msg.IsSuccess = false;
                msg.Msg = "操作失败：" + ex.Message;
            }
            return Json(msg);
        }

        public ActionResult ViewSubEnumItem(string parentId)
        {
            ViewBag.ParentId = parentId;
            return View();
        }

        [HttpPost]
        public JsonResult EnumItemList(string parentId, string typeCode, DWZPageInfo pager, DWZQueryModel where)
        {
            if (string.IsNullOrEmpty(parentId))
            {
                where.AddItem("TypeCode", typeCode);
            }
            else
            {
                where.AddItem("ParentId", parentId);
            }

            // 分页查询数据
            var list = enumItemRepo.GetPageable(pager.ToPageInfo(), where);
            var fdata = pager.ToFlexiGridData<EnumItem>(list.Page.ToList(), list.Total);

            return Json(fdata);
        }

        [HttpPost]
        public JsonResult DeleteEnumItem(string Id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();

            try
            {
                enumItemRepo.Delete(Id);
                unitOfWork.Commit();
                msg.IsSuccess = true;
                msg.Msg = "操作成功";
            }
            catch (Exception ex)
            {
                msg.IsSuccess = false;
                msg.Msg = "操作失败:" + ex.Message;
            }

            return Json(msg);
        }

        #endregion

        #region 授权管理

        [Ninject.Inject]
        public IRepository<V_QueryUserPrivilegeRoles> qupRepo { get; set; }
        [Ninject.Inject]
        public IRepository<V_UserPermissions> upRepo { get; set; }
        [Ninject.Inject]
        public IRepository<V_RoleUserRelation> urRepo { get; set; }
        [Ninject.Inject]
        public PrivilegeService privilegeService { get; set; }
        [Ninject.Inject]
        public RoleService roleService { get; set; }


        /// <summary>
        /// 获取带组织机构的用户树，异步加载
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult QueryAllUserTree(string Id)
        {
            var nodes = new List<JsonTreeNode>();
            if (string.IsNullOrEmpty(Id))
            {
                // 增加最根节点
                var rootList = OrgRepo.FindAll(o => o.ParentId == null);
                foreach (var root in rootList)
                {
                    JsonTreeNode node = new JsonTreeNode();
                    node.id = root.OrgCode;
                    node.text = root.OrgName;
                    node.value = "org";
                    node.classes = "group";
                    node.isexpand = true;
                    node.complete = true;
                    node.hasChildren = true;
                    GetChildOrgAndUser(root.OrgCode, node.ChildNodes);
                    nodes.Add(node);
                }
            }
            else
            {
                GetChildOrgAndUser(Id, nodes);
            }
            return Json(nodes);
        }

        private void GetChildOrgAndUser(string parentOrgCode, List<JsonTreeNode> parentNodes)
        {
            var glist = OrgRepo.FindAll(o => o.ParentCode == parentOrgCode);
            foreach (var item in glist)
            {
                JsonTreeNode gnode = new JsonTreeNode();
                gnode.id = item.OrgCode;
                gnode.text = item.OrgName;
                gnode.value = "org";
                gnode.hasChildren = true;
                gnode.classes = "group";
                parentNodes.Add(gnode);
            }
            var ulist = userRepo.FindAll(u => u.OrgCode == parentOrgCode);
            foreach (var user in ulist)
            {
                JsonTreeNode unode = new JsonTreeNode();
                unode.id = user.UserCode;
                unode.text = user.UserName;
                unode.value = "user";
                unode.showcheck = true;
                unode.hasChildren = false;
                unode.classes = "user";
                parentNodes.Add(unode);
            }
        }

        public ActionResult QueryAuthorization()
        {
            return View();
        }

        [HttpPost]
        public JsonResult QueryPrivilegeRoles(string userCode, string pCode)
        {
            var list = roleService.QueryUserPrivilegeRoles(userCode, pCode);
            List<string[]> rlist = new List<string[]>();
            foreach (var role in list)
            {
                rlist.Add(new string[] { role.Id.ToString(), role.RoleCode, role.RoleName, role.IsSystem ? "1" : "0" });
            }
            return Json(rlist);
        }

        [HttpPost]
        public JsonResult QueryUserPrivilegeTree(string Id, string usercode)
        {
            List<JsonTreeNode> nodes = new List<JsonTreeNode>();
            var allList = privilegeRepo.FindAll().Select(p => p.ParentId).ToList();
            var list = privilegeService.GetUserPermissions(usercode, Id);
            foreach (Privilege pri in list)
            {
                JsonTreeNode node = new JsonTreeNode();
                node.hasChildren = true;
                node.id = pri.PrivilegeCode;
                node.text = pri.PrivilegeName;
                node.value = pri.PrivilegeCode;

                // 如果是根节点，则再加载一层
                if (string.IsNullOrWhiteSpace(Id) && node.hasChildren)
                {
                    var clist = privilegeService.GetUserPermissions(usercode, node.id);
                    foreach (Privilege cpri in clist)
                    {
                        JsonTreeNode cnode = new JsonTreeNode();
                        cnode.hasChildren = allList.Contains(cpri.Id);
                        cnode.id = cpri.PrivilegeCode;
                        cnode.text = cpri.PrivilegeName;
                        cnode.value = cpri.PrivilegeCode;

                        node.ChildNodes.Add(cnode);
                    }
                    node.isexpand = true;
                    node.complete = true;
                }
                nodes.Add(node);
            }
            return Json(nodes);
        }

        [HttpPost]
        public JsonResult QueryUser(string userCode)
        {
            List<UserInfo> list = userRepo.FindAll(p => p.UserCode.Contains(userCode) || p.UserName.Contains(userCode)).ToList();
            return Json(list);
        }

        public ActionResult RoleUserRelationList(string RoleCode, string UserId)
        {
            ViewBag.RoleCode = RoleCode;
            //TODO：验证是否能管理这个角色
            return View();
        }

        [Ninject.Inject]
        public DbContext context { get; set; }

        [HttpPost]
        public JsonResult RoleUserRelationList(string roleCode, DWZPageInfo pager, DWZQueryModel where)
        {
            // 添加ParentId的检索条件
            if (!string.IsNullOrWhiteSpace(roleCode))
            {
                where.AddItem("RoleCode", roleCode);
            }

            // 分页查询数据
            var list = urRepo.GetPageable(pager.ToPageInfo(), where);
            var fdata = pager.ToFlexiGridData<V_RoleUserRelation>(list.Page.ToList(), list.Total);

            return Json(fdata);
        }

        #endregion

        #region 日志管理

        [Ninject.Inject]
        public IRepository<log> logRepo { get; set; }

        public ActionResult LogList()
        {
            return View();
        }

        [HttpPost]
        public JsonResult LogList(DWZPageInfo pager, DWZQueryModel where)
        {
            var list = logRepo.GetPageable(pager.ToPageInfo(), where);
            var fdata = pager.ToFlexiGridData<log>(list.Page.ToList(), list.Total);
            return Json(fdata);
        }

        #endregion
    }

    public class SampleData
    {
        public string id { get; set; }
        public string Name { get; set; }
        public string Code { get; set; }
    }
}
